//
//  VoiceView.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/2/4.
//

import SwiftUI
import AVFAudio
import Combine

//聊天语音试图
struct ChatItemVoiceView: View {
    var bean: SoundBean?
    var color: Color?
    @Binding var isStarted:Bool
    let click: () -> Void
    @State var player : AVAudioPlayer!
    @State var sound : ImageResource = .homeIconSound3
    @State private var timerCancellable: AnyCancellable?
    @State private var num: Int = 1
    
    var body: some View {
        HStack(spacing: 0) {
            Image(sound)
                .resizable()
                .renderingMode(.template)
                .foregroundColor(color)
                .frame(width: 18, height: 18)
            Text(bean?.getDurationStr() ?? "1")
                .font(.system(size: 12))
                .padding(.horizontal, 3)
                .foregroundColor(color)
            Text("''")
                .font(.system(size: 12))
                .foregroundColor(color)
            Spacer()
        }.frame(width: 70,height: 24)
            .padding(.horizontal,5)
            .contentShape(Rectangle())
            .onChange(of: isStarted) { newValue in
                if isStarted {
                    // 启动定时器：每秒执行一次
                    timerCancellable = Timer.publish(every: 0.3, on: .main, in: .common)
                        .autoconnect()
                        .sink(receiveValue: { _ in
                            // 根据 num 切换声音
                            switch num {
                            case 1:
                                sound = .homeIconSound1
                            case 2:
                                sound = .homeIconSound2
                            default:
                                sound = .homeIconSound3
                            }
                            // 重置计数（1→2→3→1 循环）
                            num = num == 3 ? 1 : num + 1
                        })
                } else {
                    // 停止定时器：取消订阅
                    timerCancellable?.cancel()
                    timerCancellable = nil // 释放持有，避免内存泄漏
                    sound = .homeIconSound3 // 停止后恢复默认声音
                    num = 1 // 重置计数，下次启动从 1 开始
                }
                
            }
            .onTapGesture {
                click()
            }
        
    }
}

//#Preview {
//    ChatItemVoiceView(isStarted: )
//}

//定义预览提供者
struct ChatItemVoiceView_Previews: PreviewProvider {
    static var previews: some View {
        @State var isStarted:Bool = false
        //使用预览共享配置
        configurePreviewEnvironment(for: ChatItemVoiceView(isStarted: $isStarted, click: {}))
    }
}
